importScripts('underscore.js');
console = {};
console.log = function () {
    obj = {'msg': 'console', 'args': []};
    _.each(arguments, function (arg) {
        obj.args.push(JSON.stringify(arg));
    });
    postMessage(obj);
};

var name = '';
var D = {};
var d = {};
var nexthops = {};
var neighbors = [];

var do_init = function (pname, node) {
    console.log('DO_INIT');
    d = _.clone(node);
    d[pname] = 0;
    D = _.clone(d);
    D[pname] = 0;
    _.each(node, function (neighbor) {
        nexthops[neighbor] = neighbor;
    });
    name = pname;
    neighbors = function () {
        var neighbors = [];
        _.each(d, function (value, neighbor) {
            neighbors.push(neighbor);
        });
        return neighbors;
    }();

};

var do_start = function(){
     postMessage({
        'msg': 'update',
        'nexthop': name,
        'neighbor_D': D,
        'neighbors': neighbors
    });
}

var handle_update = function (nexthop, neighbor_D) {
    console.log('NEIGHBOR UPDATE IN WORKER', name, nexthop, neighbor_D);

    updated = [];
    _.each(neighbor_D, function (dist, neighbor) {
        if (typeof D[neighbor] == 'undefined' || dist + d[nexthop] < D[neighbor]) {
            D[neighbor] = dist + d[nexthop];
            nexthop[neighbor] = nexthop;
            updated.push(neighbor);
            console.log('NEW BEST PATH', name, neighbor, D[neighbor]);
        }
    });
    updated_D = _.pick(D, updated);
    console.log('updates made in: ', updated_D);
    if (!_.isEmpty(updated_D)) {
        postMessage({
            'msg': 'update',
            'nexthop': name,
            'neighbor_D': updated_D,
            'neighbors': neighbors
        });
    }
    postMessage({
        'msg': 'computation_finished'
    });

};

onmessage = function (e) {
    if (e.data.msg == 'init') {
        do_init(e.data.name, e.data.node);
    }else if (e.data.msg == 'start'){
        do_start();
    } else if (e.data.msg == 'update') {
        handle_update(e.data['nexthop'], e.data['neighbor_D']);
    } else if (e.data.msg == 'get_final_state'){
        console.log('GET FINAL STATE', name, D);
        postMessage({
            'msg': 'finished',
            'name': name,
            'paths': D
        })
    }
};